package org.useCode.thread;

import java.util.concurrent.CountDownLatch;

/**
 * 使用CountDownLatch实现线程等待
 */
public class CoundownLatchTest01 {

    /**
     * 验证：
     */

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        System.out.println("主线程开始执行"+start);
        CountDownLatch countDownLatch = new CountDownLatch(3);

        new Thread(() -> {
            System.out.println("线程1开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        }).start();

        new Thread(() -> {
            System.out.println("线程2开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        }).start();

        new Thread(() -> {
            System.out.println("线程3开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        }).start();

        try {
            System.out.println("等待线程执行完毕");
            countDownLatch.await();
            System.out.println("线程执行完毕");
            long end = System.currentTimeMillis();
            System.out.println("主线程执行完毕所用时间:"+(end - start));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
